home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Turnbull China Bikeride
/
Turnbull China Bikeride - Disc 2.iso
/
STUTTGART
/
TEMP
/
GNU
/
bison
/
Recursion
< prev
next >
Wrap
Text File
|
1995-06-28
|
2KB
|
64 lines
Recursion
Previous: <Rules=>Rules> * Next: <Semantics=>Semantics> * Up: <Grammar File=>GrammarFil>
#Wrap on
{fH3}Recursive Rules{f}
A rule is called {fUnderline}recursive{f} when its {fStrong}result{f} nonterminal appears
also on its right hand side. Nearly all Bison grammars need to use
recursion, because that is the only way to define a sequence of any number
of somethings. Consider this recursive definition of a comma-separated
sequence of one or more expressions:
#Wrap off
#fCode
expseq1: exp
| expseq1 ',' exp
;
#f
#Wrap on
Since the recursive use of {fCode}expseq1{f} is the leftmost symbol in the
right hand side, we call this {fUnderline}left recursion{f}. By contrast, here
the same construct is defined using {fUnderline}right recursion{f}:
#Wrap off
#fCode
expseq1: exp
| exp ',' expseq1
;
#f
#Wrap on
Any kind of sequence can be defined using either left recursion or
right recursion, but you should always use left recursion, because it
can parse a sequence of any number of elements with bounded stack
space. Right recursion uses up space on the Bison stack in proportion
to the number of elements in the sequence, because all the elements
must be shifted onto the stack before the rule can be applied even
once. \*Note <Algorithm=>Algorithm>: The Bison Parser Algorithm , for
further explanation of this.
{fUnderline}Indirect{f} or {fUnderline}mutual{f} recursion occurs when the result of the
rule does not appear directly on its right hand side, but does appear
in rules for other nonterminals which do appear on its right hand
side.
For example:
#Wrap off
#fCode
expr: primary
| primary '+' primary
;
primary: constant
| '(' expr ')'
;
#f
#Wrap on
defines two mutually-recursive nonterminals, since each refers to the
other.